<template>
  <view class="login">
    <div class="header">
      <div class="logo">
        <img src="../../static/svg/logo.svg" mode="widthFix" alt="" />
      </div>
    </div>
    <div class="center">
      <button v-if="wxLogin" class="login-btn" @click="loginWx">
        微信授权登录<br />
        Login with WeChat
      </button>
      <button v-if="wxPhone" class="login-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
        授权手机号登录<br />
        Login with Phone
      </button>
    </div>
    <div class="bottom">
      <div class="wrap" @click="radio(radioType === 0 ? 1 : 0)">
        <div class="checked" :class="{ active: radioType === 1 }"></div>
        <div class="text">
          我已阅读并同意相关服务条款。 <br />
          I have read and agree to the Terms of Service
        </div>
      </div>
      <bottom-safe-area />
    </div>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getSignature, getPolicyBase64 } from '@/utils/oss'
import { clientUserLogin, clientUserInfo, registerPhone } from '@/utils/api/user'

import { useStore } from 'vuex'
const store = useStore()
let code = ref<string>('')

const name = ref<string>()
const headUrl = ref<string>()
const wxLogin = ref<Boolean>(true)
const wxPhone = ref<Boolean>(false)
const radioType = ref<number>(0)
const radio = (type) => {
  radioType.value = type
}

let openId = null
const loginWx = () => {
  // uni.showLoading()
  if (radioType.value === 0) {
    uni.showToast({
      title: '请先同意《用户协议》和《隐私政策》',
      icon: 'none'
    })
    return
  }
  uni.getUserProfile({
    desc: '展示用户信息',
    lang: 'zh_CN',
    success: (file) => {
      const { avatarUrl, city, country, gender, language, nickName, province } = JSON.parse(
        JSON.stringify(file.userInfo)
      )
      headUrl.value = avatarUrl
      name.value = nickName
      wxlogin()
    },
    fail: (err) => {
      // 用户拒绝授权
      console.log(err)
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }
  })
}

const detail = ref<any>()
const onGetPhoneNumber = (e) => {
  uni.showLoading()
  // 用户同意授权
  if (e.detail.errMsg == 'getPhoneNumber:ok') {
    e.detail.openId = openId
    detail.value = e.detail
    uni.showToast({
      title: '授权成功'
      // icon:'none'
    })
    uni.hideLoading()
    phoneLogin()
  } else {
    // 用户不同意生效
    uni.showToast({
      title: '授权失败',
      icon: 'none'
    })
    uni.hideLoading()

    // wx.reLaunch({
    //   url: '/pages/index/index',
    // })
  }
}

const wxlogin = () => {
  let data = {
    code: code.value
  }
  if (detail.value) {
    ;(data.encryptedData = detail.value.encryptedData), (data.iv = detail.value.iv)
  }
  if (uni.getStorageSync('inviteId') && uni.getStorageSync('inviteId') != 'undefined') {
    data.inviteUserId = uni.getStorageSync('inviteId')
  }
  clientUserLogin(data)
    .then((res) => {
      if (res.code == 200) {
        if (res.data.openId) {
          console.log('第一次登录时的OPENID', res.data.openId)
          wxLogin.value = false
          wxPhone.value = true
          openId = res.data.openId
        } else {
          console.log('不是第一次登录了')
          uni.setStorageSync('tokenName', res.data.saTokenInfo.tokenName)
          uni.setStorageSync('tokenValue', res.data.saTokenInfo.tokenValue)
          uni.setStorageSync('userId', res.data.saTokenInfo.loginId)
          store.dispatch('user/getUserInfo')
          uni.navigateBack()
        }
      } else {
        console.log('不是应该走这里吗?', res)
        uni.showToast({
          title: '第一次登录请授权手机号',
          icon: 'none'
        })
        uni.login({
          provider: 'weixin',
          success: (res) => {
            if (res.errMsg == 'login:ok') {
              code.value = res.code
            } else {
              uni.showToast({
                title: '系统异常，请联系管理员!'
              })
            }
          }
        })
        wxPhone.value = true
        wxLogin.value = false
      }
    })
    .catch((err) => {
      console.log('第一次登录失败的信息', JSON.stringify(err))
    })
  uni.login({
    provider: 'weixin',
    success: (res) => {
      if (res.errMsg == 'login:ok') {
        code.value = res.code
      } else {
        uni.showToast({
          title: '系统异常，请联系管理员!'
        })
      }
    }
  })
}

const phoneLogin = () => {
  console.log('手机号信息详情:', detail.value)
  registerPhone({ ...detail.value })
    .then((res) => {
      console.log('注册结果', res)
      if (res.code == 200) {
        uni.setStorageSync('tokenName', res.data.tokenName)
        uni.setStorageSync('tokenValue', res.data.tokenValue)
        uni.setStorageSync('userId', res.data.loginId)
        store.dispatch('user/getUserInfo')
        uni.navigateBack()
      }
    })
    .catch((err) => {
      console.log('注册失败结果', err)
    })
}

const handlePhone = () => {}

onMounted(() => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
      if (res.errMsg == 'login:ok') {
        code.value = res.code
        console.log(code.value, 'code值')
      } else {
        uni.showToast({
          title: '系统异常，请联系管理员!'
        })
      }
    }
  })
})
</script>

<style lang="scss">
@import './login.scss';
</style>
